<?php

/**
 * alltosun.com  dealers.php
 * ============================================================================
 * 版权所有 (C) 2009-2013 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 王德康 (wangdk@alltosun.com) $
 * $Date: 2016-1-25 下午11:56:39 $
 * $Id$
 */
class dealers_widget
{
    /**
     * 删除市场人员
     */
    public function delete_marketing($cur_user_info, $marketing_id) {
        $role_id = user_helper::get_user_role_id($cur_user_info['id']);
        if ($role_id != user_config::AGENCY) {
            return array('flag' => false, 'info' => '没有此操作权限');
        }

        // 判断解约状态
        $marketing_info = user_helper::get_user_info($marketing_id);
        if ($marketing_info) {
            if ($marketing_info['status'] == 1) {
                return array('flag' => false, 'info' => '请先解约此市场人员');
            }
            $user_marketing = _uri('user_marketing', array('marketing_id' => $marketing_id));
            if ($user_marketing) {
                if ($user_marketing['is_delete'] == 0) {
                    return array('flag' => false, 'info' => '请勿重复修改市场人员状态');
                }
            } else {
                return array('flag' => false, 'info' => '没有此市场人员信息');
            }


            $affected = _model('user_marketing')->update(array('marketing_id' => $marketing_id), array('is_delete' => 0));
            if ($affected) {
                return array('flag' => true, 'info' => '删除成功');
            } else {
                return array('flag' => false, 'info' => '网络原因,请重试');
            }
        } else {
            return array('flag' => false, 'info' => '没有市场人员信息');
        }

    }

    /**
     * 删除仓库地址
     * @param unknown_type $user_id
     * @param unknown_type $address_id
     * @return boolean
     */
    public function delete_dealer_address($user_id, $address_id) {
        $address_info = _uri('dealer_address', $address_id);
        if (!$address_info) {
            return false;
        }

        if ($address_info['user_id'] != $user_id) {
            return false;
        }

        return _model('dealer_address')->update($address_id, array('status' => 0));
    }

    /**
     * 默认仓库地址
     * @param unknown_type $province_code
     * @param unknown_type $city_code
     * @param unknown_type $county_code
     * @param unknown_type $dealer_address
     * @param unknown_type $dealer_name
     * @param unknown_type $dealer_mobile
     * @param unknown_type $is_default
     * @ 默认仓库地址要注意，设置默认值要取消其他的默认值
     */
    public function update_address($province_code, $city_code, $county_code, $dealer_address, $dealer_name, $dealer_mobile, $user_id, $address_id = 0, $is_default = 0) {
        $data['province_code'] = $province_code;
        $data['city_code'] = $city_code;
        $data['county_code'] = $county_code;
        $data['dealer_address'] = $dealer_address;
        $data['dealer_name'] = $dealer_name;
        $data['dealer_mobile'] = $dealer_mobile;
        $data['user_id'] = $user_id;

        if ($address_id) {
            $filter['id'] = $address_id;
            $filter['user_id'] = $user_id;
            return _model('dealer_address')->update($filter, $data);
        } else {
            return _model('dealer_address')->create($data);
        }
    }

    /**
     * 编辑合伙人信息
     */
    public function update_dealer_detail($cur_user_info, $dealer_id, $realname, $weixin, $bank_code, $bank_name) {
        if (!$cur_user_info) {
            return array('flag' => false, 'info' => '请先登录');
        }

        if (!$dealer_id) {
            return array('flag' => false, 'info' => '合伙人ID为空');
        }

        if (!$realname) {
            return array('flag' => false, 'info' => '合伙人姓名不能为空');
        }

        $dealer_user_info = user_helper::get_user_info($dealer_id);
        $user_info = user_helper::get_user_info($cur_user_info['id']);

        if ($dealer_user_info != $user_info) {
            return array('flag' => false, 'info' => '只能修改自己的信息');
        }

        $role_id = user_helper::get_user_role_id($cur_user_info['id']);
        if ($role_id != user_config::AGENCY) {
            return array('flag' => false, 'info' => '没有此操作权限');
        }

        $dealer_info = array(
            'realname' => $realname,
            'weixin' => $weixin,
            'bank_code' => $bank_code,
            'bank_name' => $bank_name
        );

        $filter = array_merge($dealer_info, array('id' => $dealer_id));
        $filter_user_info = user_helper::get_user_info_by_filter($filter);
        if ($filter_user_info) {
            return array('flag' => false, 'info' => '修改成功');
        } else {
            $affected = user_helper::update_user_info($dealer_id, $dealer_info);
            if ($affected) {
                return array('flag' => false, 'info' => '修改成功');
            } else {
                return array('flag' => false, 'info' => '网络原因,请重新提交');
            }
        }
    }

    /**
     * 编辑市场人员
     * @param unknown $cur_user_info
     * @param unknown $marketing_id
     * @param unknown $realname
     * @param unknown $bank_name
     * @param unknown $bank_cardno
     * @param unknown $idcard
     * @param unknown $gender
     * @param unknown $email
     * @param unknown $qq
     * @param unknown $weixin
     * @param unknown $department
     * @param unknown $job
     */
    public function update_marketing_detail($cur_user_info, $marketing_id, $realname, $bank_name, $bank_cardno, $idcard, $gender, $email, $qq, $weixin, $department, $job) {
        if (!$cur_user_info) {
            return array('flag' => false, 'info' => '请先登录');
        }

        if (!$marketing_id) {
            return array('flag' => false, 'info' => '市场人员ID为空');
        }

        if (!$realname) {
            return array('flag' => false, 'info' => '请正确的填写真实姓名');
        }

        $gender_list = user_config::$user_gender_type;
        if (!$gender_list[$gender]) {
            return array('flag' => false, 'info' => '请正确的填写真实姓名');
        }

        if ($email) {
            if (!user_helper::is_email($email)) {
                return array('flag' => false, 'info' => '邮箱格式不正确');
            }
        }

        $user_info = _uri('user', $marketing_id);
        if (!$user_info) {
            return array('flag' => false, 'info' => '市场人员信息不存在');
        }

        if ($cur_user_info['role_type'] != user_config::AGENCY) {
            return array('flag' => false, 'info' => '没有此操作权限');
        }

        if ($user_info['status'] == 0) {
            return array('flag' => false, 'info' => '请先恢复市场人员再进行信息修改');
        }

        $user_data = array();
        $user_data['realname'] = $realname;
        $user_data['qq'] = $qq;
        $user_data['weixin'] = $weixin;
        $user_data['email'] = $email;
        $user_data['gender'] = $gender;

        $user_affected = 0;
        $filter_user_info = user_helper::get_user_info_by_filter(array_merge($user_data, array('id' => $marketing_id)));
        if ($filter_user_info) {
            $user_affected = 1;
        } else {
            $user_affected = user_helper::update_user_info($marketing_id, $user_data);
        }

        if (!$user_affected) {
            return array('flag' => false, 'info' => '网络问题，请重新提交');
        }

        $user_marketing_data = array();
        $user_marketing_data['bank_name'] = $bank_name;
        $user_marketing_data['bank_cardno'] = $bank_cardno;
        $user_marketing_data['idcard'] = $idcard;
        $user_marketing_data['department'] = $department;
        $user_marketing_data['job'] = $job;
        $user_marketing_data['update_time'] = date('Y-m-d H:i:s');

        $affected = _model('user_marketing')->update(array('marketing_id' => $marketing_id), $user_marketing_data);
        if ($affected) {
            return array('flag' => true, 'info' => '修改成功');
        } else {
            return array('flag' => false, 'info' => '网络问题，请重新提交');
        }
    }

    /**
     * TODO 即将废弃
     * 支付凭证
     * @param unknown $user_id
     * @param unknown $order_id
     * @param unknown $payoff_person
     * @param unknown $payoff_time
     * @param unknown $payoff_extra
     * @return multitype:boolean string |multitype:boolean unknown
     */
    public function create_payoff($user_id, $order_id, $payoff_person, $payoff_money, $payoff_time, $payoff_extra) {
        if (!$order_id) {
            return array('flag' => false, 'info' => '订单号不存在');
        }

        if (!is_numeric($order_id)) {
            return array('flag' => false, 'info' => $order_id);
        }

        if (!$payoff_person || !$payoff_time || !$payoff_money) {
            return array('flag' => false, 'info' => '支付凭证信息不全');
        }

        $reg = '/\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?/';
        if (!preg_match($reg, $payoff_time)) {
            return array('flag' => false, 'info' => '日期格式不正确');
        }

        if (!is_numeric($payoff_money)) {
            return array('flag' => false, 'info' => '付款金额格式不正确');
        }

        $order_info = _uri('order', $order_id);
        if (!$order_info) {
            return array('flag' => false, 'info' => '此订单不存在');
        }

        if ($order_info['is_payoff']) {
            return array('flag' => false, 'info' => '此支付凭证已审核不能修改');
        }

        if ($order_info['progress'] != 1) {
            return array('flag' => false, 'info' => '此支付凭证已审核不能修改');
        }

        $info = array(
            'payoff_person' => $payoff_person,
            'payoff_money' => $payoff_money,
            'payoff_time' => $payoff_time,
            'payoff_extra' => $payoff_extra
        );

        _model('order')->update($order_id, $info);

        if (!$order_info['payoff_person']) {
            // 短信通知销售助理
            _widget('dealers.message')->create_payoff_message($user_id, $order_id);
        }

        return array('flag' => true, 'info' => '提交成功');

    }


    /**
     * 市场人员旗下门店批量转移,@wangdk 2016-04-26支持跨合伙人迁移
     * @param unknown_type $ower_ids
     * @param unknown_type $market_id
     * @return 返回转移成功的门店数量
     * 1、迁移门店不能有未完成的订单
     * 2、迁移经销商必须真实有效
     * 3、迁移后市场人员统一为合伙人
     */
    public function market_store_to_other($owner_ids, $market_id, $agency_id = 0) {
        $succ_num = 0;
        $error = '门店迁移失败';
        $result = array();
        if ($owner_ids && is_array($owner_ids)) {

            foreach ($owner_ids as $owner_id) {
                $result[] = dealers_helper::user_store_to_market($owner_id, $market_id, $agency_id);
            }

            if (count($result) > 1) {
                // 多门店迁移
                foreach ($result as $v) {
                    if ($v[0]) {
                        $succ_num++;
                    }
                }
            } else {
                // 单门店迁移
                if (isset($result[0])) {
                    if ($result[0][0]) {
                        $succ_num = 1;
                    } else {
                        $error = $result[0][1];
                    }
                }
            }
        }

        return array($succ_num, $error);
    }

    /**
     * 经销商确认收货的处理
     * @param unknown_type $store_user_info
     * @param unknown_type $store_id
     * @param unknown_type $store_info
     * @param unknown_type $order_info
     * @param unknown_type $order_id
     */
    public function confirm_order_arrival($store_user_info, $store_id, $store_info, $order_info, $order_id) {
        //经销商确认收货处理

        //换算积分
        $return_score_data = _widget('score_record')->format_store_order_score($store_id, $order_info['goods_num'], $order_info['price']);

        //如果是一级经销商，直接加积分
        if ($store_user_info['dealer_level'] == 1) {
            //收货成功增加积分和发消息
            _widget('score_record')->change_score($store_info['user_id'], $store_id, $order_info['id'], $return_score_data['score']);
        } else { //如果是二级经销商，需要给一级经销商加积分
            //给二级经销商增加积分
            _widget('score_record')->change_score($store_info['user_id'], $store_id, $order_info['id'], $return_score_data['score']);
            //给一级经销商增加积分
            $dealer_one_store_info = store_helper::get_user_store($store_user_info['parent_id']);
            _widget('score_record')->change_score($store_user_info['parent_id'], $dealer_one_store_info['id'], $order_info['id'], $return_score_data['score_one']);
        }

        //处理商品信息
        $order_relation_list = order_helper::get_order_relation_by_order_id($order_info['id'], '', array('status' => 1));
        foreach ($order_relation_list as $key => $value) {
            $store_goods_info = store_helper::get_store_goods_info(array(
                'goods_id' => $value['goods_id'],
                'store_id' => $order_info['store_id']
            ));
            $goods_info = goods_helper::get_goods_info($value['goods_id']);
            //看商户库存里面有没有这个商品，如果没有就添加一条
            if (!$store_goods_info) {
                goods_helper::create_store_goods(array(
                    'user_id' => $order_info['user_id'],
                    'goods_id' => $value['goods_id'],
                    'store_id' => $order_info['store_id'],
                    'status' => 1
                ));
            }
            $dealers_store_info = store_helper::get_store($order_info['store_id']);

            $dealers_user_store_info = store_helper::get_user_store($dealers_store_info['owner_id']);

            $store_info_sku_info = goods_helper::get_store_goods_sku_info(array(
                'sku_id' => $value['sku_id'],
                'store_id' => $dealers_user_store_info['id'],
                'goods_id' => $value['goods_id']
            ));

            // 看下商户库存里面有没有这个商品的sku信息，如果有的话增加库存并上架，如果没有插入一条并上架
            if ($store_info_sku_info) {
                goods_helper::update_store_goods_sku(array('id' => $store_info_sku_info['id']), ' SET `stock` = `stock`+' .
                                                                                                $value['goods_num']);
            } else {
                goods_helper::create_store_goods_sku(array(
                    'user_id' => $order_info['user_id'],
                    'goods_id' => $value['goods_id'],
                    'store_id' => $dealers_user_store_info['id'],
                    'sku_id' => $value['sku_id'],
                    'price' => $goods_info['market_price'],
                    'stock' => $value['goods_num'],
                    'sale_count' => 0,
                    'status' => 1
                ));
            }
        }

        // 更新订单时间
        order_helper::update_order_time($order_info['id'], 'receiver_time');

        _widget('dealers.message')->confirm_finished_message($store_user_info, $order_info);

        // 杯子别捣乱!
        // 杯数计算
        $order_cup_list = cup_helper::get_order_cup_data($order_info['id']);
        if ($order_cup_list) {
            $return_status = cup_helper::save_cup_data($order_info['store_id'], $order_cup_list);
            //if (!$return_status) {
            //    api_helper::return_data(1, '经销商杯数计算不正确，请重新操作');
            //}
        }
    }

    /**
     * 经销商更改市场人员解约还是正常
     */
    public function change_people_status($user_id, $marketing_id, $status) {
        if (!$marketing_id) {
            return array('flag' => false, 'info' => '市场人员未知');
        }

        $role_id = user_helper::get_user_role_id($user_id);

        if ($role_id != user_config::AGENCY) {
            return array('flag' => false, 'info' => '没有此操作权限');
        }

        $marketing_info = dealers_helper::get_dealers_staff_info($marketing_id);
        if (!$marketing_info) {
            return array('flag' => false, 'info' => '没有此市场人员信息');
        }
        if ($user_id != $marketing_info['agency_id']) {
            return array('flag' => false, 'info' => '没有此操作权限');
        }

        if ($status == $marketing_info['status']) {
            return array('flag' => false, 'info' => '请勿重复修改市场人员状态');
        }


        if (0 == $status) {
            $store_list = store_helper::get_store_list_by_dealer_id($user_id, array('marketing_id' => $marketing_id));
            if ($store_list) {
                return array('flag' => false, 'info' => '请先转移签约的门店');
            }

            $no_deliver_num = order_helper::get_order_num_by_progress(array(
                1,
                3,
                5
            ), 5, array('assigned_id' => $marketing_id, 'is_enable' => array(0, 1)));
            if ($no_deliver_num) {
                return array('flag' => false, 'info' => '此市场人员下有未完成的订单,不能执行解约操作');
            }
        }

        // 事务修改
        ts_helper::begin();
        try {

            $affected_row = ts_helper::_model('user_marketing')->update($marketing_info['id'], array('status' => $status));

            if ($affected_row) {
                $affected = ts_helper::_model('user')->update($marketing_id, array('status' => $status));
                if (!$affected) {
                    ts_helper::rollback();
                    return array('flag' => false, 'info' => '操作失败');
                }
            } else {
                ts_helper::rollback();
                return array('flag' => false, 'info' => '操作失败');
            }

            ts_helper::commit();

        } catch (Exception $e) {
            ts_helper::trace_log($e);
            ts_helper::rollback();
        }

        return array('flag' => true, 'info' => '操作成功');

    }

}